package com.ycsj.goldmedalnewconcept.teacher.activity;

import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.ycsj.common.adapter.ShowPicGvAdapter;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.base.SpKeys;
import com.ycsj.common.manager.BqaManager;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.manager.SrfManager;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.SPUtil;
import com.ycsj.common.utils.StateBarUtil;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.common.view.dialog.AlertDialogUtil;
import com.ycsj.common.view.scroll.MyGridView;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.Constants;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.bean.ResultInfo;
import com.ycsj.goldmedalnewconcept.common.bean.TkItemBean;
import com.ycsj.goldmedalnewconcept.common.http.HttpCallBack;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.teacher.adapter.AssignQuestionRvAdapter;
import com.ycsj.goldmedalnewconcept.teacher.adapter.WorkSutdentGvAdapter;
import com.ycsj.goldmedalnewconcept.teacher.bean.StudentTel;
import com.ycsj.goldmedalnewconcept.teacher.bean.TkAssignHomeWorkInfo;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * 教师端-题库-布置练习
 * Created by Kevin on 2019/2/21
 */
public class TeacherTKAssignHomeworkActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.srf)
    SmartRefreshLayout srf;
    @BindView(R.id.rl_loading)
    RelativeLayout rlLoading;

    @BindView(R.id.rl_layout)
    RelativeLayout rl_layout;

    //添加题目
    @BindView(R.id.lv_add_question)
    ImageView lvAddQuestion;

    //创建练习
    @BindView(R.id.lv_create_homework)
    ImageView lvCreateHomework;

    //跟布局
    private LinearLayout llMain;
    //顶部布局
    private LinearLayout rlMain;
    //展示所有学生的GridView
    private MyGridView mgv;
    //展开布局
    private LinearLayout llShow;
    //打开列表
    private TextView tvShow;

    //展示学生信息的数据集合
    private List<TkAssignHomeWorkInfo.StuBean> oldDatas;

    // 初次从服务器请求的学生的全部数据
    private List<TkAssignHomeWorkInfo.StuBean> newDatas;

    //展示学生列表的适配器
    private WorkSutdentGvAdapter workSutdentGvAdapter;

    //适配对象
    private ShowPicGvAdapter adapter;

    //标题栏的布局
    private LinearLayout llTitle;

    // 初次从服务器请求的学生的全部数据
    private List<StudentTel> stuList;

    //班级ID
    private String userclass;

    private TextView tvTitle;

    private ImageView ivBack;

    private ImageView lvPreview;

    //列表数据
    public List<TkItemBean> questionOldDatas;

    //列表适配器
    private AssignQuestionRvAdapter questionAdapter;

    //删除题目
    public static int TKType = 400;

    private boolean isChange = false;

    //题目ID
    private String questionID = "";

    //学生草稿信息
    private String stel;

    //题目草稿信息
    private String content;

    //总数
    private int total;

    //携带的单元号
    private int unit;

    public static final int SUBMITREF = 0x320;

    //班级ID
    private String classnum;

    //添加题目后的更新表示
    public static final int ADDQUESTIONUPDATE = 0x440;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_teacher_tk_assignhomework;
    }

    @Override
    protected void init() {

        //初始化视图
        initView();

        //通知栏沉浸式
        initStateBar();

        //初始化标题栏
        initTitle();

        //设置展示学生列表的GridView
        initGv();

        //请求服务器
        httpMethod();

    }

    /**
     * 设置题目数据
     */
    private void initData() {

        //关闭下拉刷新
        SrfManager.setSmartByPullListener(srf, null);

        questionAdapter = new AssignQuestionRvAdapter(TeacherTKAssignHomeworkActivity.this, R.layout.item_rv_assign_question, questionOldDatas, 0);
        BqaManager.setRv(null, TeacherTKAssignHomeworkActivity.this, questionAdapter, rv);

        if (questionOldDatas.size() > 19) {
            lvAddQuestion.setImageResource(R.drawable.teacher_tk_un_addquestion);
        } else {
            lvAddQuestion.setImageResource(R.drawable.teacher_tk_addquestion);
        }
    }


    /**
     * 初始化视图的方法
     */
    public void initView() {

        //获取单元号
        unit = getIntent().getIntExtra("unit", -1);
        //获取班级ID
        userclass = AccountUtils.getTeacherClass(this);

        rlMain = findViewById(R.id.ll_title);
        mgv = findViewById(R.id.mgv);
        tvShow = findViewById(R.id.tv_show);
        tvTitle = findViewById(R.id.tv_title);
        tvShow.setOnClickListener(this);
        llShow = findViewById(R.id.ll_show);
        llMain = findViewById(R.id.ll_main);
        //标题栏
        llTitle = findViewById(R.id.ll_title);
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        lvPreview = findViewById(R.id.lv_edit);
        ivBack.setOnClickListener(this);

        lvAddQuestion.setOnClickListener(this);
        lvCreateHomework.setOnClickListener(this);
        lvPreview.setOnClickListener(this);

        rl_layout.setVisibility(View.GONE);


    }

    /**
     * 初始化标题栏
     */
    private void initTitle() {
        tvTitle.setText("布置课堂练习");
        lvPreview.setVisibility(View.VISIBLE);
        lvPreview.setImageResource(R.drawable.tk_clickable_preview);
    }

    /**
     * 沉浸状态栏
     */
    protected void initStateBar() {
        StateBarUtil.customImmerseBar(this);
    }

    /**
     * 请求服务器获取数据
     */
    private void httpMethod() {

        classnum = SPUtil.getString(this, SpKeys.TEACHERCLASS);

        Map<String, String> map = new HashMap<>();
        map.put("jobmsg", "4");
        map.put("ttel", AccountUtils.getAccount(this));
        map.put("classnum", classnum);
        map.put("unit", unit + "");

        HttpUtils.post(HttpAddress.TKASSIGNHOMEWORK, map, this,
                new HttpCallBack<TkAssignHomeWorkInfo>() {

                    @Override
                    public void onSuccess(TkAssignHomeWorkInfo info) {

                        rl_layout.setVisibility(View.VISIBLE);
                        rlLoading.setVisibility(View.GONE);
                        if (null != info && info.getState() == 1) {

                            //返回成功
                            //学生列表数据
                            total = info.getTotal();
                            newDatas = info.getStu();
                            questionOldDatas = info.getData();
                            if (newDatas != null) {

                                //设置学生数据
                                syncStuData();

                            }
                            if (questionOldDatas != null) {
                                //设置数据
                                initData();
                            }

                        } else {
                            ToastUtils.showShort(Constants.ERRORSTATE + info.getState());
                        }
                    }

                    @Override
                    public void onError(String e) {
                        rlLoading.setVisibility(View.GONE);
                        ToastUtils.showShort(Constants.ERRORSTATE);
                    }
                });
    }


    /**
     * 获取服务器数据后同步学生列表的数据
     */
    private void syncStuData() {

        //清空原有的数据集合
        oldDatas.clear();

        for (int i = 0; i < newDatas.size(); i++) {
            if ("1".equals(newDatas.get(i).getState())) {
                newDatas.get(i).flag = true;
            }
        }

        // 证明有数据
        if (newDatas.size() <= 4) {
            // 如果少于4个学生不需要显示打开列表的提醒按钮
            llShow.setVisibility(View.GONE);
            tvShow.setText("关闭列表");
            // 小于4个的时候将数据全部添加到oldDatas中
            oldDatas.addAll(newDatas);
        } else {
            // 返回的学生大于4个则显示打开里列表的提醒按钮
            llShow.setVisibility(View.VISIBLE);
            tvShow.setText("打开列表");
            for (int i = 0; i < 4; i++) {
                oldDatas.add(newDatas.get(i));
            }
        }
        // 通知适配器刷新数据
        workSutdentGvAdapter.notifyDataSetChanged();
    }

    /**
     * 初始化展示学生的GridView
     */
    private void initGv() {
        newDatas = new ArrayList<>();
        oldDatas = new ArrayList<>();
        questionOldDatas = new ArrayList<>();

        workSutdentGvAdapter = new WorkSutdentGvAdapter(this, oldDatas,
                R.layout.teacher_item_gb_students);
        mgv.setAdapter(workSutdentGvAdapter);
    }


    /**
     * 页面控件点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.iv_back:
                //判断是否修改了题目
                if (isChange) {
                    if (questionOldDatas == null || questionOldDatas.size() == 0) {
                        //退出
                        finish();
                    } else {
                        //是否保存草稿
                        isSave();
                    }
                } else {
                    //退出
                    finish();
                }
                break;
            case R.id.lv_edit:
                //预览
                //判断是否20道题
                if (questionOldDatas.size() == 0) {
                    UiUtils.Toast("题目不能为空，请添加题目后创建", false);
                } else {

                    //拼接数据
                    saveData();

                }
                if (questionOldDatas.size() != 0) {

                    String questionList = GsonUtil.listToJson(questionOldDatas);

                    Intent it = new Intent(this, TeacherTKHomeworkPreviewActivity.class);
                    it.putExtra("questionList", questionList);
                    it.putExtra("stel", stel);
                    it.putExtra("total", total + "");
                    it.putExtra("content", content);
                    it.putExtra("unit", unit + "");
                    startActivity(it);

                } else {
                    ToastUtils.showShort("请添加题目");
                }
                break;
            case R.id.tv_show:
                //全部打开和关闭的操作
                doOpenOrCloseAction();
                break;
            case R.id.lv_add_question:
                //判断题目是否超过最大值
                if (questionOldDatas.size() > 19) {
                    AlertDialogUtil.showAlertDialogSimple(true, this,
                            "本单元练习最多20道，请先删除题目后再添加新的题目", new AlertDialogUtil.onListener() {
                                @Override
                                public void onClickOk() {
                                }

                                @Override
                                public void onClickDismiss() {

                                }

                            });
                } else {
                    if (questionOldDatas.size() == 0) {
                        questionID = "";
                    } else {
                        //添加的题目
                        for (int i = 0; i < questionOldDatas.size(); i++) {
                            if (TextUtils.isEmpty(questionID)) {
                                questionID += questionOldDatas.get(i).getTypeid() + "-" + questionOldDatas.get(i).getId_D();
                            } else {
                                questionID += "_" + questionOldDatas.get(i).getTypeid() + "-" + questionOldDatas.get(i).getId_D();
                            }
                        }
                    }

                    //添加题目
                    TeacherAddQuestionsActivity.goActivity(this, "", unit + "", questionID, (20 - questionOldDatas.size()));
                }
                break;
            case R.id.lv_create_homework:
                //判断是否20道题
                if (questionOldDatas.size() == 0) {
                    UiUtils.Toast("题目不能为空，请添加题目后创建", false);
                } else {

                    //拼接数据
                    saveData();
                    if (TextUtils.isEmpty(stel)) {
                        ToastUtils.showShort("请选择要布置练习的学生");
                        break;
                    }
                    //创建练习
                    Intent intent = new Intent(this, TeacherCreateHomeworkActivity.class);
                    intent.putExtra("stel", stel);
                    intent.putExtra("total", total + "");
                    intent.putExtra("content", content);
                    intent.putExtra("unit", unit + "");

                    startActivity(intent);
                }
                break;
        }
    }

    /**
     * 是否保存草稿
     */
    private void isSave() {
        AlertDialogUtil.showAlertDialog(true, this, "将此次编辑保留？", new AlertDialogUtil.onListener() {
            @Override
            public void onClickOk() {
                rlLoading.setVisibility(View.VISIBLE);
                //保存草稿
                saveQuestion();
            }

            @Override
            public void onClickDismiss() {
                //退出
                finish();
            }
        });
    }


    /**
     * 保存至草稿箱
     */
    private void saveQuestion() {
        CustomDialogManager.show(this, "上传中...");
        //拼接数据
        saveData();

        Map<String, String> map = new HashMap<>();
        map.put("jobmsg", "9");
        map.put("ttel", AccountUtils.getAccount(this));
        map.put("classnum", AccountUtils.getTeacherClass(this));
        map.put("unit", unit + "");
        map.put("stel", stel);
        map.put("total", total + "");
        map.put("content", content);

        HttpUtils.post(HttpAddress.TKASSIGNHOMEWORK, map, this,
                new HttpCallBack<ResultInfo>() {

                    @Override
                    public void onSuccess(ResultInfo info) {
                        rlLoading.setVisibility(View.GONE);
                        if ("1".equals(info.getState())) {
                            //返回成功
                            UiUtils.Toast("保存草稿成功", true);

                            BusInfo busInfo = new BusInfo();
                            busInfo.type = SUBMITREF;
                            EventBus.getDefault().post(busInfo);
                            CustomDialogManager.dissmiss();
                            finish();

                        } else {
                            CustomDialogManager.dissmiss();
                            UiUtils.Toast(Constants.ERRORSTATE + info.getState(), false);
                            Log.i("test", Constants.ERRORSTATE + info.getState());
                        }
                    }

                    @Override
                    public void onError(String e) {
                        CustomDialogManager.dissmiss();
                        rlLoading.setVisibility(View.GONE);
                    }
                });
    }


    /**
     * 拼接数据参数
     */
    private void saveData() {
        stel = "";
        content = "";

        //选中的学生
        for (int i = 0; i < newDatas.size(); i++) {
            if (!newDatas.get(i).flag) {
                if (TextUtils.isEmpty(stel)) {
                    stel += newDatas.get(i).getName() + "€" + newDatas.get(i).getSttel();
                } else {
                    stel += "￠" + newDatas.get(i).getName() + "€" + newDatas.get(i).getSttel();
                }
            }
        }

        //添加的题目
        for (int i = 0; i < questionOldDatas.size(); i++) {
            if (TextUtils.isEmpty(content)) {
                content += questionOldDatas.get(i).getTypeid() + "-" + questionOldDatas.get(i).getId_D();
            } else {
                content += "_" + questionOldDatas.get(i).getTypeid() + "-" + questionOldDatas.get(i).getId_D();
            }
        }
    }


    /**
     * 事件处理
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo && busInfo.type == TKType) {
            //是否修改的标识
            isChange = true;
            //删除题目
            int pos = busInfo.questionPosition;
            questionOldDatas.remove(pos);
            questionAdapter.notifyDataSetChanged();


            if (questionOldDatas.size() > 19) {
                lvAddQuestion.setImageResource(R.drawable.teacher_tk_un_addquestion);
            } else {
                lvAddQuestion.setImageResource(R.drawable.teacher_tk_addquestion);
            }

        } else if (null != busInfo && busInfo.type == TeacherCreateHomeworkActivity.SUBMITSUC) {
            //布置练习成功后关闭当前界面
            finish();
        } else if (null != busInfo && ADDQUESTIONUPDATE == busInfo.type) {
            isChange = true;
            //添加练习成功后更新界面
            String content = busInfo.msg;
            List<TkItemBean> newDatas = GsonUtil.jsonToList(content, TkItemBean[].class);
            questionOldDatas.addAll(newDatas);
            questionAdapter.notifyDataSetChanged();

            if (questionOldDatas.size() > 19) {
                lvAddQuestion.setImageResource(R.drawable.teacher_tk_un_addquestion);
            } else {
                lvAddQuestion.setImageResource(R.drawable.teacher_tk_addquestion);
            }

        }
    }


    /**
     * 展示显示全部学生列表和收拢学生列表的操作
     */
    private void doOpenOrCloseAction() {
        // 点击打开列表
        if ("打开列表".equals(tvShow.getText())) {
            // GridView显示全部学生数据
            oldDatas.clear();
            oldDatas.addAll(newDatas);
            workSutdentGvAdapter.notifyDataSetChanged();
            tvShow.setText("关闭列表");
            tvShow.setBackgroundResource(R.drawable.teacher_studentlist_uppull);
        } else if ("关闭列表".equals(tvShow.getText())) {
            // GridView只显示4条数据
            oldDatas.clear();
            for (int i = 0; i < 4; i++) {
                oldDatas.add(newDatas.get(i));
            }
            workSutdentGvAdapter.notifyDataSetChanged();
            tvShow.setText("打开列表");
            tvShow.setBackgroundResource(R.drawable.teacher_studentlist_downpull);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                //判断是否修改了题目
                if (isChange) {
                    if (questionOldDatas == null || questionOldDatas.size() == 0) {
                        //退出
                        finish();
                    } else {
                        //是否保存草稿
                        isSave();
                    }
                } else {
                    //退出
                    finish();
                }
                break;
        }
        return super.onKeyDown(keyCode, event);
    }
}
